package cn.cyb.server.service;

import cn.cyb.server.common.constant.Constants;
import cn.cyb.server.common.utils.JwtUtils;
import cn.cyb.server.common.utils.StringUtils;
import cn.cyb.server.domain.entity.SysUser;
import cn.cyb.server.domain.model.LoginUser;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yuebo
 * @date 2024/12/25
 */
@Component
public class TokenService {

    private Logger logger = LoggerFactory.getLogger(TokenService.class);

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", loginUser.getSysUser().getUserId());
        claims.put("userName", loginUser.getSysUser().getUserName());
        int hour = 60 * 60 * 1000;
        return JwtUtils.genToken(claims, new Date(System.currentTimeMillis() + hour));
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        String jwt = getToken(request);
        if (StringUtils.isNotEmpty(jwt)) {
            try {
                Claims claims = JwtUtils.parseToken(jwt);
                logger.info("claims={}", claims);
                String userName = (String) claims.get("userName");

                SysUser user = sysUserService.selectUserByUserName(userName);
                if (user != null) {
                    return new LoginUser(user);
                }
            } catch (Exception e) {
                logger.error("获取用户信息异常", e);
            }
        }
        return null;
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            // Authorization: Bearer Token
            token = token.replace(Constants.TOKEN_PREFIX, "");
        } else {
            // vue_admin_template项目
            token = request.getHeader("X-Token");
        }
        return token;
    }
}
